package com.slofzx.nuoda.evaluation.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.slofzx.nuoda.common.config.SystemConfig;
import com.slofzx.nuoda.common.dao.CompanyDAO;
import com.slofzx.nuoda.common.dao.SysUserDAO;
import com.slofzx.nuoda.common.dto.CompanyDTO;
import com.slofzx.nuoda.common.dto.PageDTO;
import com.slofzx.nuoda.common.dto.UserQueryDTO;
import com.slofzx.nuoda.common.entity.Company;
import com.slofzx.nuoda.common.entity.SysUser;
import com.slofzx.nuoda.common.enums.CacheTypeEnum;
import com.slofzx.nuoda.common.enums.CommonResultEnum;
import com.slofzx.nuoda.common.enums.ServiceResult;
import com.slofzx.nuoda.common.exception.ServiceException;
import com.slofzx.nuoda.common.feign.OfficeClient;
import com.slofzx.nuoda.common.service.CompanyService;
import com.slofzx.nuoda.common.service.impl.BaseServiceImpl;
import com.slofzx.nuoda.common.util.CacheUtil;
import com.slofzx.nuoda.common.vo.CompanyVO;
import com.slofzx.nuoda.common.vo.SysUserVO;
import com.slofzx.nuoda.evaluation.dao.SsoOfficeDAO;
import com.slofzx.nuoda.evaluation.dao.SsoUserDAO;
import com.slofzx.nuoda.evaluation.entity.SsoOffice;
import com.slofzx.nuoda.evaluation.entity.SsoUser;
import com.slofzx.nuoda.evaluation.enums.CustomOfficeTypeEnum;
import com.slofzx.nuoda.evaluation.service.SyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SyncServiceImpl extends BaseServiceImpl implements SyncService {
    private static final List<String> OFFICE_EXCLUDE_LIST = Arrays.asList("23243","101463","995117046","21946","995114191");
    @Autowired
    private SsoUserDAO ssoUserDAO;
    @Autowired
    private SysUserDAO sysUserDAO;
    @Autowired
    private CompanyDAO companyDAO;
    @Autowired
    private SsoOfficeDAO ssoOfficeDAO;
    @Autowired
    protected SystemConfig systemConfig;
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult syncUser() {
        final List<SsoUser> ssoUsers = ssoUserDAO.queryNewUserList();
        if (CollectionUtils.isEmpty(ssoUsers)) {
            throw new ServiceException("没有新增的用户，请推送后再同步","",null);
        }
        final String userId = getUserId();
        List<SysUser> userList = new ArrayList<>();
        UserQueryDTO userQueryDTO = new UserQueryDTO();
        userQueryDTO.setPageSize(PageDTO.ALL);
        List<SysUser> sysUserList = sysUserDAO.findList(userQueryDTO);
        Map<String, SysUser> sysUserMap = sysUserList.stream().collect(Collectors.toMap(SysUser::getId, Function.identity()));
        boolean hasAdmin = false;
        for (SsoUser ssoUser : ssoUsers) {
            final SysUser sysUser = JSON.parseObject(JSON.toJSONString(ssoUser), SysUser.class);
            sysUser.setOfficeId(sysUser.getCompanyId());
            if (sysUser.getId().equals("1")) {
                hasAdmin = true;
                sysUser.setCompanyId("0");
            }
            if (sysUserMap.containsKey(sysUser.getId())) {
                SysUser user = sysUserMap.get(sysUser.getId());
                if ("21810".equals(user.getOfficeId())) {
                    sysUser.setOfficeId("21810");
                    sysUser.setCompanyId("21810");
                }
                if (hasAdmin) {
                    sysUser.setPassword(sysUser.getPassword());
                }

            }
            sysUser.setCreateTime(new Date());
            sysUser.setCreateUser(userId);
            userList.add(sysUser);
            CacheUtil.remove(CacheTypeEnum.USER, "user_id_cache_" + ssoUser.getId());
        }
        // 如果不存在管理员用户则写入管理员
        if (!hasAdmin) {
            UserQueryDTO dto = new UserQueryDTO();
            dto.setId("1");
            List<SysUser> daoList = sysUserDAO.findList(dto);
            if (daoList != null && !daoList.isEmpty()) {
                SysUser sysUser = daoList.get(0);
                sysUser.setCompanyId("0");
                sysUser.setId("1");
                userList.add(sysUser);
            }
        }
        sysUserDAO.delete(new QueryWrapper<>());
        saveBatch(userList, sysUserDAO, SysUser.class);
        return CommonResultEnum.SUCCESS;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServiceResult syncOffice() {

        final List<SsoOffice> ssoOffices = ssoOfficeDAO.queryNewOfficeList();
        SysUserVO user = getUser();
        String userId = user.getId();
        List<Company> companyList = companyDAO.queryList(new CompanyDTO());
        //companyList 转换为map id为key
        Map<String, Company> companyMap = new HashMap<>();
        for (Company company : companyList) {
            companyMap.put(company.getId(), company);
            CacheUtil.remove("sys:office:" + company.getId());
            CacheUtil.remove("sys:office:tree:" + company.getId());
            CacheUtil.remove("sys:office::code:tree:" + company.getCode());
//            CompanyDTO dto = new CompanyDTO();
//            dto.setId(company.getId());
//            companyService.delete(dto);
        }

        List<Company> officeList = new ArrayList<>();
        for (SsoOffice ssoOffice : ssoOffices) {
            final SsoOffice office = JSON.parseObject(JSON.toJSONString(ssoOffice), SsoOffice.class);
            if (OFFICE_EXCLUDE_LIST.contains(office.getId())) {
                office.setParentId("21810");
            }
            String id = office.getId();
            if ("21810".equals(id)) {
                office.setParentId("0");
            }
            if (companyMap.containsKey(id)) {
                Company company = companyMap.get(id);
                office.setType(company.getType());
                String shortName = company.getShortName();
                office.setShortName(shortName);
                if (StringUtils.isEmpty(shortName)) {
                    office.setShortName(office.getName());
                }
                office.setCode(company.getCode());
            }
            office.setCreateTime(new Date());
            office.setCreateUser(userId);
            officeList.add(office);

        }
//        if(Objects.equals(user.getCompanyId(),systemConfig.getOfficeRoot()) == false) {
//            CompanyVO vo = get(user.getCompanyId());
//            if(CustomOfficeTypeEnum.getEnum(vo.getType()) == CustomOfficeTypeEnum.RESEARCH){
//                targetCompanyId = systemConfig.getOfficeRoot();
//            }
//        }
        CacheUtil.remove("sys:office:tree"+user.getCompanyId() );
        CacheUtil.remove("sys:office:tree:" + this.systemConfig.getOfficeRoot());
        CacheUtil.remove("sys:office::code:tree:" + this.systemConfig.getOfficeRoot());
        companyDAO.deleteBatchIds(companyMap.keySet());
        saveBatch(officeList, companyDAO, Company.class);
        return CommonResultEnum.SUCCESS;
    }
}
